﻿using System;
using System.Data.Linq;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using Cjc.Data.Mapping;

namespace SampleDataModel.LinqToSql
{
	public class LinqToSqlMappingContextInfo<TDataContext> : IMappingContextInfo
		where TDataContext : DataContext, new()
	{
		public ExpressionTranslator CreateExpressionTranslator()
		{
			return new ExpressionTranslator( typeof( TDataContext ) );
		}

		public object CreateContext( object providerSpecification, TextWriter log )
		{
			return new TDataContext();
		}

		public IQueryProvider GetQueryProvider( object context )
		{
			var dc = context as DataContext;

			// All DC tables are also IQueryProviders, so just return the first one
			return (IQueryProvider)dc.GetTable( dc.Mapping.GetTables().First().RowType.Type );
		}

		public void SubmitChanges( object context )
		{
			( context as DataContext ).SubmitChanges();
		}

		public bool MustInlineInvokes { get { return false; } }

		public Type GetEntityType( string typeName )
		{
			return Type.GetType( typeof( TDataContext ).Namespace + "." + typeName );
		}

		public Type GetEntityAssociationType( string typeName )
		{
			return typeof( EntitySet<> ).MakeGenericType( GetEntityType( typeName ) );
		}

		public LambdaExpression GetEntitiesMethod( Type type )
		{
			var context = Expression.Parameter( typeof( TDataContext ), "dc" );

			return Expression.Lambda( Expression.Call( context, "GetTable", new[] { type } ), context );
		}

		public virtual LambdaExpression GetXmlMethod( TypeCode typeCode )
		{
			return null;
		}

		public virtual LambdaExpression GetLookupMethod( TypeCode typeCode )
		{
			return null;
		}
	}
}